﻿using EyFramework.Common;
using EyFramework.Library;
using EyFramework.Sys.Core.Dao;
using EyFramework.Sys.Core.Service;
using EyFramework.Sys.Entity;
using EyFramework.Sys.Entity.Dto;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using EyFramework.Common.Entity;
using EyFramework.Common.Utils;
using System.IO;

namespace EyFramework.Main
{
    public partial class FrmLogin : FrmDevBase
    {
        private StartUpArgs startUpArgs;
        private IniFileUtil iniFile = new IniFileUtil(Path.Combine(DirectoryUtil.GetCurrentDirectory(), "AutoUpdate.ini"));
        public FrmLogin()
        {
            InitializeComponent();
        }

        public FrmLogin(StartUpArgs args)
        {
            InitializeComponent();
            startUpArgs = args;
        }

        private void FrmLogin_Load(object sender, EventArgs e)
        {
            labelControl5.Text = "V"+ iniFile.IniReadValue("AutoUpdate", "AppVersion");
            InitSysList();
            if (startUpArgs != null)
            {
                tbAccount.Text = startUpArgs.LOGINNAME;
                tbPassword.Text = startUpArgs.PASSWORD;
                lueSys.EditValue = startUpArgs.SYSID;
                CheckLogin();
            }
        }

        /// <summary>
        /// 检查本地版本是否需要更新
        /// </summary>
        private void CheckUpdate()
        {
            if (Globals.CheckUpdate())
            {
                if (Globals.ShowYesNoAndTips("发现更新的版本，是否立即更新？") == DialogResult.Yes)
                {
                    Globals.StartUpdate();
                }
            }
        }

        /// <summary>
        /// 异步初始化数据连接，初始化系统列表
        /// </summary>
        private void InitSysList()
        {
            this.ShowLoginInfo("正在初始化系统列表...");
            Task task = new Task(() =>
            {
                ISysListService sysListService = new SysListService(new SysListDao());
                var sysList = sysListService.GetAllActiveSys();
                BindSys(sysList);
            });
            task.Start();
        }

        private void BindSys(List<SysList> sysLists)
        {
            Action act = delegate ()
            {
                var sys = (from c in sysLists select new SysListDto { SYS_ID = c.SYS_ID, SYS_NAME = c.SYS_NAME }).ToList();
                DataBinder.BindingLookupEditDataSource(lueSys, sys, "SYS_NAME", "SYS_ID");
                string LastRunSysId = Globals.GetSysConfig(Constants.CFG_LastRunSysId);
                if (!string.IsNullOrEmpty(LastRunSysId))
                {
                    lueSys.EditValue = long.Parse(LastRunSysId);
                }
                this.ShowLoginInfo("准备就绪...");
            };
            this.BeginInvoke(act);
        }

        /// <summary>
        /// 显示登陆窗体.(公共静态方法)
        /// </summary>
        public static bool Login(StartUpArgs args)
        {
            FrmLogin form = new FrmLogin(args);
            var result = form.ShowDialog();
            return result == DialogResult.OK;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            CheckLogin();
        }

        private void ShowLoginInfo(string info)
        {
            lblLoadingInfo.Text = info;
            lblLoadingInfo.Update();
        }

        private void SetButtonEnable(bool value)
        {
            btnLogin.Enabled = value;
            btnCancel.Enabled = value;
            btnLogin.Update();
            btnCancel.Update();
        }

        private void tbAccount_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13 && !string.IsNullOrEmpty(tbAccount.Text.Trim()))
            {
                tbPassword.Select();
            }
        }

        private void tbPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue != 13) return;
            if (lueSys.EditValue != null)
            {
                CheckLogin();
            }
            else
            {
                lueSys.Select();
            }
        }

        private bool CheckData()
        {
            if (string.IsNullOrEmpty(tbAccount.Text.Trim()))
            {
                Globals.ShowWarning("登录账号不能为空!");
                tbAccount.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(tbPassword.Text.Trim()))
            {
                Globals.ShowWarning("登录密码不能为空!");
                tbPassword.Focus();
                return false;
            }
            if (lueSys.EditValue == null)
            {
                Globals.ShowWarning("登录子系统不能为空，请选择需要登录的子系统!");
                lueSys.Focus();
                return false;
            }
            return true;
        }

        #region 业务方法

        private void CheckLogin()
        {
            if (!CheckData()) return;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                this.SetButtonEnable(false);
                this.Update();//必须
                this.ShowLoginInfo("开始校验用户名密码...");
                var scUserService = Globals.GetService<ISysUserService>();
                Func<object> action = () =>
                {
                    return scUserService.CheckAccount(tbAccount.Text.Trim(), tbPassword.Text.Trim());
                };
                var user = (SysUser)DoTaskAsync(action);
                this.ShowLoginInfo("登录成功...");
                SaveLoginUser(user);
                var mainForm = new FrmMain();
                mainForm.InitUserInterface(new LoadStatus(lblLoadingInfo));
                FormGlobals.MainForm = mainForm;
                this.DialogResult = DialogResult.OK; //成功
                this.Hide();
                this.Close(); //关闭登陆窗体
            }
            catch (Exception ex)
            {
                this.ShowLoginInfo(ex.Message);
                Globals.ShowException(ex);
                this.Cursor = Cursors.Default;
                this.SetButtonEnable(true);
            }
        }

        #endregion 业务方法

        /// <summary>
        /// 保存登录信息
        /// </summary>
        /// <param name="user"></param>
        public void SaveLoginUser(SysUser user)
        {
            //缓存登录用户信息
            LoginUser loginUser = new LoginUser();
            if (startUpArgs != null)
            {
                SysList sys = new SysListService(new SysListDao()).GetSysListById(startUpArgs.SYSID);
                loginUser.SysId = sys.SYS_ID.ToString();
                loginUser.SysName = sys.SYS_NAME;
            }
            else
            {
                loginUser.SysId = lueSys.EditValue.ToString();
                loginUser.SysName = lueSys.Text.Trim();
            }
            loginUser.LoginName = user.USER_NAME;
            loginUser.Password = user.PASSWORD;
            loginUser.StaffName = user.NICK_NAME;
            loginUser.UserId = user.USER_ID;
            Globals.CurrentUser = loginUser;
            Globals.SetSysConfig(Constants.CFG_LastRunSysId, loginUser.SysId);
            //记录登录日志
        }

        private void lueSys_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                CheckLogin();
            }
        }

        private void picRefresh_Click(object sender, EventArgs e)
        {
            InitSysList();
        }

        private void FrmLogin_Shown(object sender, EventArgs e)
        {
            CheckUpdate();
        }
    }
}